/*@author:Rachel*/
package pku.ss.movieSystem.common;

import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import daos.Comment;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class CommentUtils {

	public final static void setRequestAttr(HttpServletRequest request, ComPaginationSupport ps,
			int startIndex, int movieId) {
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("comments", ps.getJsonArray());
		int[] indexes = ps.getIndexes();
		String indexesStr = "";
		for(int i=0;i<indexes.length-1;i++) {
			indexesStr += indexes[i] + ",";
		}
		if(indexes.length>0)
			indexesStr = "[" + indexesStr + indexes[indexes.length-1] + "]";
		else 
			indexesStr = "[]";
		
		request.setAttribute("commentsResults", jsonObj);
		request.setAttribute("pageSize", ps.getPageSize());
		request.setAttribute("totalCount", ps.getTotalCount());
		request.setAttribute("indexes", indexesStr);
		request.setAttribute("startIndex", startIndex);
		
		request.setAttribute("movieId", movieId);
	}
	
	public final static String commentsObjToJson(List<Comment> comments) {

		JSONObject temp = new JSONObject();
		JSONArray _array = new JSONArray();
		
		if(comments != null && comments.size()>0) {
			
			for(int i=0;i<comments.size();i++) {
				
				temp.put("commentID", comments.get(i).getCommentId());
				temp.put("commentUserId", comments.get(i).getUser().getUserId());
				temp.put("commentUserPicSrc", comments.get(i).getUser().getAddress());
				temp.put("commentUserName", comments.get(i).getUser().getUserName());
				temp.put("commentTimeStamp", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(comments.get(i).getComTimeStamp()));
				temp.put("commentContent", comments.get(i).getContent());
				
				_array.add(temp);
			}
		}
		
		return _array.toString();
	}
}
